package com.star.learn.excel.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class ThreadPoolConfig {

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        //创建线程池对象（Spring 封装的线程池）
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取 CPU 核心数
        int core = Runtime.getRuntime().availableProcessors();
        //设置核心线程数（最小线程数）
        executor.setCorePoolSize(core);
        //最大线程数（满载后最多创建多少个线程）
        executor.setMaxPoolSize(core * 2);
        //队列容量，线程满了之后，排队的任务数量上限
        executor.setQueueCapacity(1000);
        //非核心线程闲置多久被销毁
        executor.setKeepAliveSeconds(60);
        //设置线程名，便于日志排查
        executor.setThreadNamePrefix("Executor-");
        //应用关闭时，是否等待任务执行完
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //最多等待多少秒后强制关闭线程池
        executor.setAwaitTerminationSeconds(30);
        //初始化线程池
        executor.initialize();
        return executor;
    }
}